import axios from 'axios';
import router from '../router';
import store from '../vuex/store';
import {Message} from 'element-ui'

axios.interceptors.response.use(function (response) {
    // 在发送请求之前做些什么
    return response;
  }, function (error) {
    // 对请求错误做些什么
    console.log(error)
    if(error.response && error.response.status === 401){
        Message.error('授权已过期,请重新登录')
        store.commit('logout', 'false')
        router.push({ path: '/login' })
    }
    // return Promise.reject(error);
  });


// let host = 'http://192.168.0.185:11990'
let host = 'https://beedex.org/ausd'

// 登录请求方法
const loginreq = (method, url, params) => {
    return axios({
        method: method,
        url: host+url,
        headers: {
            'Content-Type': 'application/json',
        },
        data: params,
        // traditional: true,
        // transformRequest: [
        //     function(data) {
        //         let ret = ''
        //         for (let it in data) {
        //             ret +=
        //                 encodeURIComponent(it) +
        //                 '=' +
        //                 encodeURIComponent(data[it]) +
        //                 '&'
        //         }
        //         return ret
        //     }
        // ]
    }).then(res => res.data);
};
// 通用公用方法
const req = (method, url, params) => {
    return axios({
        method: method,
        url: host+url,
        headers: {
            'Content-Type': 'application/json',
            CMToken: localStorage.getItem('logintoken')
        },
        data: params,
        // traditional: true,
        // transformRequest: [
        //     function(data) {
        //         let ret = ''
        //         for (let it in data) {
        //             ret +=
        //                 encodeURIComponent(it) +
        //                 '=' +
        //                 encodeURIComponent(data[it]) +
        //                 '&'
        //         }
        //         return ret
        //     }
        // ]
    }).then(res => {
        if(res && res.data){
            return res.data
        }
        return res
    })
    // .catch(err =>{
    //     console.log(err)
    // });
};

const upHttp = async(url,parms)=>{
    let obj = {
        method: 'post',
        headers: {
          'CMToken': localStorage.getItem('logintoken')
      }
    }
    if(parms){
        obj.body = parms
        // obj.redirect = 'follow'
    }
    try {
        const response = await fetch(host+url,obj);
        if(response.status == 200){
            return response.json();
        }else if(response.status == 401){
            return
        }else{
            console.log('response error')
            console.log(response)
        }
    } catch(err) {
        console.log(err);
    }
}

export {
    loginreq,
    req,
    upHttp
}